package com.quanyan.assets.service.impl;

import com.quanyan.api.APIRequest;
import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.AssetsPayReceive;
import com.quanyan.api.enums.AssetsType;
import com.quanyan.assets.constants.AssetsConstants;
import com.quanyan.assets.emun.AssetsErrorEnum;
import com.quanyan.assets.emun.OpType;
import com.quanyan.assets.emun.StatusType;
import com.quanyan.assets.entity.AccumulateAssets;
import com.quanyan.assets.entity.TbUserAssets;
import com.quanyan.assets.entity.TbUserEggsAccumulateHistory;
import com.quanyan.assets.mapper.ETbUserEggsAccumulateHistoryMapper;
import com.quanyan.assets.repository.EggsAccumulateHistoryRepository;
import com.quanyan.assets.repository.UserAssetsRepository;
import com.quanyan.assets.request.ReqAccumulateRefund;
import com.quanyan.assets.service.UtilAccumulateService;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.exception.BizException;
import com.quanyan.common.utils.CommonUtils;
import com.quanyan.user.response.RespUserInfoBase;
import com.quanyan.user.serviceFacade.UserServiceFacade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wmb on 2016/11/22.
 */
@Service("utilAccumulateService")
public class UtilAccumulateServiceImpl implements UtilAccumulateService{
    @Autowired
    private EggsAccumulateHistoryRepository eggsAccumulateHistoryRepository;
    @Autowired
    private UserAssetsRepository userAssetsRepository;
    @Autowired
    private UserServiceFacade userServiceFacade;
    @Autowired
    private ETbUserEggsAccumulateHistoryMapper eTbUserEggsAccumulateHistoryMapper;
    private Logger logger = LoggerFactory.getLogger(UtilAccumulateService.class);
    @Override
    public void refundAccumulateSubmit(ReqAccumulateRefund reqAccumulateRefund) {
        List<TbUserAssets> tbUserAssetsList = new ArrayList<TbUserAssets>();
        List<AccumulateAssets> accumulateAssetsList = reqAccumulateRefund.getAccumulateAssetsList();
        for (AccumulateAssets accumulateAssets : accumulateAssetsList) {
            //鸟蛋
            if (accumulateAssets.getAssetsType() == AssetsType.ASSETS_EGGS.id.byteValue()) {
                if (null == accumulateAssets.getAccumulate() || accumulateAssets.getAccumulate() <= 0) {
                    throw new BizException(AssetsErrorEnum.ACCUMULATE_IS_INVALID);
                }
                //冻结退款金额
                int updateRefundAmount = eggsAccumulateHistoryRepository.updateRefundSubmit(reqAccumulateRefund.getSystemCode(), reqAccumulateRefund.getBusinessCode(), reqAccumulateRefund.getBusinessNo(), accumulateAssets.getAccumulate());
                if (updateRefundAmount == 0) {
                    throw new BizException(AssetsErrorEnum.REFUND_IS_NOT_ENOUGH);
                }
            }
        }
    }

    @Override
    public void refundAccumulateSuccess(ReqAccumulateRefund reqAccumulateRefund) {
        //退款成功
        reqAccumulateRefund.setStatus(StatusType.EFFECTIVE.id.byteValue());
        refundComplate(reqAccumulateRefund);
    }

    @Override
    public void refundAccumulateFail(ReqAccumulateRefund reqAccumulateRefund) {
        //退款失败
        reqAccumulateRefund.setStatus(StatusType.DISABLE.id.byteValue());
        refundComplate(reqAccumulateRefund);
    }

    @Override
    public void repairPhoneNickName() {
        List<TbUserEggsAccumulateHistory> tbUserEggsAccumulateHistoryList = eTbUserEggsAccumulateHistoryMapper.selectRepairPhoneNickName();
        for(TbUserEggsAccumulateHistory tbUserEggsAccumulateHistory : tbUserEggsAccumulateHistoryList){
            APIResponse<RespUserInfoBase> apiResponse = userServiceFacade.queryUserInfo(tbUserEggsAccumulateHistory.getUid());
            if(apiResponse.isRet()){
                TbUserEggsAccumulateHistory updateTbUserEggsAccumulateHistory = new TbUserEggsAccumulateHistory();
                updateTbUserEggsAccumulateHistory.setMobile(apiResponse.getData().getMobile());
                updateTbUserEggsAccumulateHistory.setNickName(apiResponse.getData().getNickName());
                updateTbUserEggsAccumulateHistory.setId(tbUserEggsAccumulateHistory.getId());
                eTbUserEggsAccumulateHistoryMapper.repairPhoneNickName(updateTbUserEggsAccumulateHistory);
            }

        }
    }

    private void refundComplate(ReqAccumulateRefund reqAccumulateRefund) {
        List<TbUserAssets> tbUserAssetsList = new ArrayList<TbUserAssets>();
        List<AccumulateAssets> accumulateAssetsList = reqAccumulateRefund.getAccumulateAssetsList();
        for (AccumulateAssets accumulateAssets : accumulateAssetsList) {
            //鸟蛋
            if (accumulateAssets.getAssetsType() == AssetsType.ASSETS_EGGS.id.byteValue()) {
                if (null == accumulateAssets.getAccumulate() || accumulateAssets.getAccumulate() <= 0) {
                    throw new BizException(AssetsErrorEnum.ACCUMULATE_IS_INVALID);
                }
                //解冻退款金额
                int updateRefundAmount = eggsAccumulateHistoryRepository.updateRefundComplate(reqAccumulateRefund.getSystemCode(), reqAccumulateRefund.getBusinessCode(), reqAccumulateRefund.getBusinessNo(), accumulateAssets.getAccumulate(),reqAccumulateRefund.getStatus());
                if (updateRefundAmount == 1&&reqAccumulateRefund.getStatus().equals(StatusType.EFFECTIVE.id.byteValue())) {
                    //更新成功可以直接获取历史记录
                    TbUserEggsAccumulateHistory tbUserEggsAccumulateHistory = eggsAccumulateHistoryRepository.selectByBusinessNo(reqAccumulateRefund.getSystemCode(), reqAccumulateRefund.getBusinessNo(), OpType.CONSUME.id.byteValue());
                    //更新用户积分
                    int updateUserAccumulate = userAssetsRepository.updateEffectiveAccumulate(tbUserEggsAccumulateHistory.getUid(), AssetsType.ASSETS_EGGS.id.byteValue(), accumulateAssets.getAccumulate());
                    if (updateUserAccumulate == 1) {
                        //插入退款记录
                        String serialNumber = CommonUtils.generateBusinessOrderNo(Constants.ASSETS_SYSTEM, tbUserEggsAccumulateHistory.getUid());
                        TbUserEggsAccumulateHistory insert = new TbUserEggsAccumulateHistory();
                        try {
                            APIResponse<RespUserInfoBase> apiResponse = userServiceFacade.queryUserInfo(tbUserEggsAccumulateHistory.getUid());
                            if(apiResponse.isRet()){
                                insert.setReceiver(apiResponse.getData().getNickName());
                                insert.setMobile(apiResponse.getData().getMobile());
                                insert.setNickName(apiResponse.getData().getNickName());
                            }
                        }catch (Exception e){

                        }
                        insert.setUid(tbUserEggsAccumulateHistory.getUid());
                        insert.setBusinessNo(tbUserEggsAccumulateHistory.getBusinessNo());
                        insert.setAccumulate(accumulateAssets.getAccumulate());
                        insert.setOpType(OpType.RECEIVE.id.byteValue());
                        insert.setBusinessId(tbUserEggsAccumulateHistory.getBusinessId());
                        insert.setBusinessCode(getRefundCodeBySystemCode(tbUserEggsAccumulateHistory.getSystemCode()));
                        insert.setSystemCode(tbUserEggsAccumulateHistory.getSystemCode());
                        insert.setpDescribe("订单退款");
                        insert.setStatus(StatusType.EFFECTIVE.id.byteValue());
                        insert.setPayReceive(AssetsPayReceive.RETURN.getName());
                        insert.setInfo((reqAccumulateRefund.getInfo() == null) ? tbUserEggsAccumulateHistory.getInfo() + "退款" : reqAccumulateRefund.getInfo());
                        insert.setSerialNumber(serialNumber);
                        eggsAccumulateHistoryRepository.insertAccumulateHistory(insert);
                        TbUserAssets tbUserAssets = userAssetsRepository.selectByUidAndAssetsType(tbUserEggsAccumulateHistory.getUid(), AssetsType.ASSETS_EGGS.id.byteValue());
                        tbUserAssetsList.add(tbUserAssets);
                    } else {
                        throw new BizException(AssetsErrorEnum.UPDATE_ACCUMULATE_HISTORY_ERROR);
                    }
                } else if(updateRefundAmount==0){
                    throw new BizException(AssetsErrorEnum.REFUND_IS_NOT_ENOUGH);
                }else if(reqAccumulateRefund.getStatus().equals(StatusType.DISABLE.id.byteValue())){
                    //失败退款不做记录
                }
            }
        }
    }

    private String getRefundCodeBySystemCode(String systemCode) {
        if(Constants.CLUB_SYSTEM_CODE.equals(systemCode)){
            return AssetsConstants.CLUB_REFUND_CODE;
        }else if(Constants.TRAVEL_SYSTEM_CODE.equals(systemCode)){
            return AssetsConstants.TRAVEL_REFUND_CODE;
        }else if(Constants.STADIUM_SYSTEM_CODE.equals(systemCode)){
            return AssetsConstants.STADIUM_REFUND_CODE;
        }else if(Constants.PLACE_SYSTEM_CODE.equals(systemCode)){
            return AssetsConstants.PLACE_REFUND_CODE;
        }else if(Constants.AUCTION_SYSTEM_CODE.equals(systemCode)){
            return AssetsConstants.AUCTION_REFUND_CODE;
        }else if(Constants.ONEPRICE_SYSTEM_CODE.equals(systemCode)){
            return AssetsConstants.ONEPRICE_REFUND_CODE;
        }else if(Constants.DAREN_SPARRING_SYSTEM_CODE.equals(systemCode)){
            return AssetsConstants.DAREN_SPARRING_REFUND_CODE;
        }else{
            return null;
        }

    }
}
